package com.yhq.basic.design.singleton;

import java.io.Serializable;

/**
 * 单例模式
 * 懒汉式-方法加锁
 * 增加防止序列号破解单例，和范式的破解单例的措施
 *
 * @author hqyin
 * @date 2023/2/3 11:00 上午
 */
public class Singleton7 implements Serializable {
    private static Singleton7 INSTANCE = null;

    private Singleton7() {
        synchronized (Singleton7.class) {
            if (INSTANCE != null) {
                throw new RuntimeException("防止反射破解单例");
            }
        }
    }

    public static synchronized Singleton7 getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton7();
        }
        return INSTANCE;
    }

    /**
     * 防止序列化破坏，有readResolve的话将会调用该方法返回结果，具体源代码在ObjectInputStream中的readOrdinaryObject方法中。
     *
     * @return
     */
    private Object readResolve() {
        return INSTANCE;
    }
}
